using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;

#if UNITY_EDITOR
using UnityEditor;
#endif

public class WorkFlowManager : MonoBehaviour
{
    public static WorkFlowManager instance;

    private string playerName = "";
    private int bestScore = 0;

    private void Awake() {
        if (instance == null) {
            instance = this;
            PresetData();
            DontDestroyOnLoad(gameObject);
            return;
        }
        Destroy(gameObject);
    }
    
    public string GetPlayerName() {
        return playerName;
    }

    public void SetPlayerName(string playerNameNew) {
        playerName = playerNameNew;
    }

    public int GetBestScore() {
        return bestScore;
    }

    public void UpdateBestScoreBy(int score) {
        if (score > bestScore) {
            bestScore = score;
        }
    }

    [System.Serializable]
    public class PlayerBasic {
        public string name;
        public int score;
    }

    public void SaveData() {
        PlayerBasic playerBasic = new PlayerBasic();
        playerBasic.name = playerName;
        playerBasic.score = bestScore;
        string json = JsonUtility.ToJson(playerBasic);
        string fileName = GetJsonFileName();
        File.WriteAllText(fileName, json);
        Debug.Log("save on :" + fileName);
    }

    public PlayerBasic GetData() {
        string fileName = GetJsonFileName();
        if(File.Exists(fileName)) {
            string json = File.ReadAllText(GetJsonFileName());
            return JsonUtility.FromJson<PlayerBasic>(json);
        }
        return null;
    }

    public void PresetData() {
        PlayerBasic playerBasic = GetData();
        if (playerBasic == null) {
            return;
        }
        SetPlayerName(playerBasic.name);
        UpdateBestScoreBy(playerBasic.score);
    }

    public string GetJsonFileName() {
        return Application.persistentDataPath + "/player-list.json";
    }

    public void StartGame() {
        SceneManager.LoadScene("main");
    }

    public void QuitGame() {
        SaveData();
        #if UNITY_EDITOR
        EditorApplication.ExitPlaymode();
        #else
        Application.Quit();
        #endif
    }
}
